import { reactive, ref, onMounted, onBeforeMount, nextTick, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { usePublicHooks } from "../hooks";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'
import { $t } from "@/plugins/i18n";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { locationsList, getCategory, addLocations, updateLocations, UpdateStatus, AppointOut, DelteLoad, Initialize, Attribute, excelLocations, delLocations, Ldristance, getLocations } from '@/utils/api/BasicManagement/locations'
import { GetAllshelves } from '@/utils/api/BasicManagement/shelves'
import { GetAllStation } from '@/utils/api/dispatch/station'
import { EmptyOut } from '@/utils/api/dispatch/job'
import { agvModels } from '@/utils/api/dispatch/agv'

export function useDept() {
    const { locale } = useTranslationLang(); // 获取语言
    const form = reactive({
        code: "",
        state: null,
        rackid: null,
        stationName: '',
        pageNumber: 0,
        pageSize: 10,
        sortName: "code",
        sortType: 0,
        attribute: "",
        lrdistance: null,
        lrdistance2: null,
        rotationangle: null,
        column: null,
        layer: null,
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });
    // 状态select
    const statusSelect = reactive([
        { value: 1, label: $t('racklocations.idle') },
        { value: 2, label: $t('racklocations.disable') },
        { value: 3, label: $t('racklocations.locked') },
        { value: 4, label: $t('racklocations.cargoAlreadyLoaded') },
        // { value: 5, label: '无货箱' },
    ])
    // 是否旋转
    const rotateList = reactive([
        { value: 0, name: $t('racklocations.no') },
        { value: 1, name: $t('racklocations.yes') },
    ])
    // 货架select
    let rackselect = ref([])
    // 类别select
    let categorySelect = ref([])
    // 站点select
    let stationSelect = ref([])
    // 车型
    let agvModel = ref([])
    // 货位类型
    let attributeSelect = ref([])
    // 左右伸缩距离
    let lrdistanceList = ref([])


    function formatState(status) {
        const stateMap = {
            1: $t('racklocations.idle'),
            2: $t('racklocations.disable'),
            3: $t('racklocations.locked'),
            4: $t('racklocations.cargoAlreadyLoaded'),
            // 5: '无货箱'
        }
        return stateMap[status]
    }

    function rotationangleState(status) {
        const stateMap = {
            1: $t('racklocations.left'),
            2: $t('racklocations.right'),
        }
        return stateMap[status]
    }

    function vehicletypeState(status) {
        if (status) {
            const agvObj = agvModel.value.find(item => item.Code == status)
            return agvObj.Name
        } else {
            return ''
        }
    }

    function siteQuery(status) {
        if (status) {
            let obj = stationSelect.value.find(s => s.stationid === status)
            if (obj) {
                return obj.stationname
            } else {
                return ''
            }
        } else {
            return ''
        }
    }

    function formatAttribute(status) {
        const stateMap = {
            0: '普通货位',
            1: '入库区',
            2: '出库区'
        }
        return stateMap[status]
    }

    const columns = ref<any>([
        {
            id: 1,
            isShow: true,
            label: $t('racklocations.locationCode'),
            prop: "code",
            width: 180,
            align: "left",
            sortable: true
        },
        {
            id: 2,
            isShow: true,
            label: $t('racklocations.locationType'),
            prop: "AttributeName",
            width: 100,
            align: "left"
        },
        {
            id: 3,
            isShow: true,
            label: $t('racklocations.correspondingSite'),
            prop: "auxiliary",
            width: 100,
            align: "left",
            formatter: ({ auxiliary }) => { return siteQuery(auxiliary) }

        },
        {
            id: 4,
            isShow: true,
            label: $t('racklocations.accessHeight'),
            prop: "lochigh",
            width: 120,
            align: "left"
        },
        {
            id: 5,
            isShow: true,
            label: $t('racklocations.heightAfterLifting'),
            prop: "lifthigh",
            width: 120,
            align: "left"
        },
        {
            id: 6,
            isShow: true,
            label: $t('racklocations.status'),
            prop: "status",
            minWidth: 100,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.status)}>
                    {formatState(row.status)}
                </el-tag>
            )
        },
        {
            id: 7,
            isShow: true,
            label: $t('racklocations.shelf'),
            prop: "ShelvesName",
            width: 100,
            align: "left",
            sortable: true
        },
        {
            id: 8,
            isShow: true,
            label: $t('racklocations.numberOfLayers'),
            prop: "layer",
            width: 80,
            align: "left",
            sortable: true
        },
        {
            id: 9,
            isShow: true,
            label: $t('racklocations.column'),
            prop: "row",
            width: 80,
            align: "left",
            sortable: true
        },

        {
            id: 10,
            isShow: true,
            label: $t('racklocations.compensationForPickUp'),
            prop: "lrdistance",
            width: 110,
            align: "left",
            // sortable: true
        },
        {
            id: 11,
            isShow: true,
            label: $t('racklocations.compensationForReleaseOfGoods'),
            prop: "lrdistance2",
            width: 110,
            align: "left",
            // sortable: true
        },
        {
            id: 12,
            isShow: true,
            label: $t('racklocations.longitudinalSeparation'),
            prop: "liftside",
            width: 100,
            align: "left",
            // sortable: true
        },
        {
            id: 13,
            isShow: true,
            label: $t('racklocations.rotationDirection'),
            prop: "rotationangle",
            width: 100,
            align: "left",
            formatter: ({ rotationangle }) => { return rotationangleState(rotationangle); }
        },
        {
            id: 14,
            isShow: true,
            label: $t('racklocations.agvModel'),
            prop: "vehicletype",
            width: 120,
            align: "left",
            formatter: ({ vehicletype }) => { return vehicletypeState(vehicletype); }
        },
        {
            id: 15,
            isShow: true,
            label: $t('racklocations.stationInFrontOfTheCargoLocation'),
            prop: "PreStationName",
            width: 120,
            align: "left",
            // sortable: true
        },
        {
            id: 60,
            isShow: true,
            label: $t('racklocations.remarks'),
            prop: "note",
            minWidth: 200,
            align: "left"
        },
        {
            id: 66,
            isShow: true,
            label: $t('racklocations.operation'),
            fixed: "right",
            width: 150,
            slot: "operation"
        }
    ])

    function tableReloading() {
        return [
            {
                id: 1,
                isShow: true,
                label: $t('racklocations.locationCode'),
                prop: "code",
                width: 180,
                align: "left",
                sortable: true
            },
            {
                id: 2,
                isShow: true,
                label: $t('racklocations.locationType'),
                prop: "AttributeName",
                width: 100,
                align: "left"
            },
            {
                id: 3,
                isShow: true,
                label: $t('racklocations.correspondingSite'),
                prop: "auxiliary",
                width: 100,
                align: "left",
                formatter: ({ auxiliary }) => { return siteQuery(auxiliary) }

            },
            {
                id: 4,
                isShow: true,
                label: $t('racklocations.accessHeight'),
                prop: "lochigh",
                width: 120,
                align: "left"
            },
            {
                id: 5,
                isShow: true,
                label: $t('racklocations.heightAfterLifting'),
                prop: "lifthigh",
                width: 120,
                align: "left"
            },
            {
                id: 6,
                isShow: true,
                label: $t('racklocations.status'),
                prop: "status",
                minWidth: 100,
                cellRenderer: ({ row, props }) => (
                    <el-tag size={props.size} style={tagStyle.value(row.status)}>
                        {formatState(row.status)}
                    </el-tag>
                )
            },
            {
                id: 7,
                isShow: true,
                label: $t('racklocations.shelf'),
                prop: "ShelvesName",
                width: 100,
                align: "left",
                sortable: true
            },
            {
                id: 8,
                isShow: true,
                label: $t('racklocations.numberOfLayers'),
                prop: "layer",
                width: 80,
                align: "left",
                sortable: true
            },
            {
                id: 9,
                isShow: true,
                label: $t('racklocations.column'),
                prop: "row",
                width: 80,
                align: "left",
                sortable: true
            },

            {
                id: 10,
                isShow: true,
                label: $t('racklocations.compensationForPickUp'),
                prop: "lrdistance",
                width: 110,
                align: "left",
                // sortable: true
            },
            {
                id: 11,
                isShow: true,
                label: $t('racklocations.compensationForReleaseOfGoods'),
                prop: "lrdistance2",
                width: 110,
                align: "left",
                // sortable: true
            },
            {
                id: 12,
                isShow: true,
                label: $t('racklocations.longitudinalSeparation'),
                prop: "liftside",
                width: 100,
                align: "left",
                // sortable: true
            },
            {
                id: 13,
                isShow: true,
                label: $t('racklocations.rotationDirection'),
                prop: "rotationangle",
                width: 100,
                align: "left",
                formatter: ({ rotationangle }) => { return rotationangleState(rotationangle); }
            },
            {
                id: 14,
                isShow: true,
                label: $t('racklocations.agvModel'),
                prop: "vehicletype",
                width: 120,
                align: "left",
                formatter: ({ vehicletype }) => { return vehicletypeState(vehicletype); }
            },
            {
                id: 15,
                isShow: true,
                label: $t('racklocations.stationInFrontOfTheCargoLocation'),
                prop: "PreStationName",
                width: 120,
                align: "left",
                // sortable: true
            },
            {
                id: 60,
                isShow: true,
                label: $t('racklocations.remarks'),
                prop: "note",
                minWidth: 200,
                align: "left"
            },
            {
                id: 66,
                isShow: true,
                label: $t('racklocations.operation'),
                fixed: "right",
                width: 150,
                slot: "operation"
            }
        ]
    }

    async function onSearch() {
        loading.value = true;
        const { Content } = await locationsList(form);
        let newData = Content.Results;
        dataList.value = newData;
        pagination.total = Content.TotalCount;
        pagination.pageSize = Content.PageSize;
        pagination.currentPage = Content.PageNumber + 1;

        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    function newAddDialog(title, row) {
        const newTitle = title === "新增" ? $t('racklocations.addNewStorageLocation') : $t('racklocations.editCargoLocation')
        addDialog({
            title: newTitle,
            props: {
                formInline: {
                    code: row?.code ?? "",
                    warehouseid: row?.warehouseid ?? null,
                    shelvesid: row?.shelvesid ?? null,
                    layer: row?.layer ?? null,
                    row: row?.row ?? null,
                    length: row?.length ?? null,
                    width: row?.width ?? null,
                    height: row?.height ?? null,
                    bearing: row?.bearing ?? null,
                    status: row?.status ?? 1,
                    sort: row?.sort ?? null,
                    note: row?.note ?? null,
                    rotationangle: row?.rotationangle ?? null,
                    lrdistance: row?.lrdistance ?? 0,
                    lrdistance2: row?.lrdistance2 ?? 0,
                    stationList: row?.stationList ?? [{}],
                    auxiliary: row?.auxiliary ?? null,
                    prestaid: row?.prestaid ?? null,
                    lochigh: row?.lochigh ?? 0,
                    lifthigh: row?.lifthigh ?? 0,
                    liftside: row?.liftside ?? 0,
                    vehicletype: row?.vehicletype ?? "",
                    attribute: row?.attribute ?? "",
                    correct: row?.correct ?? null,
                },
                statusSelect,
                attributeSelect,
                rackselect: rackselect.value,
                stationSelect: stationSelect.value,
                rotateList: rotateList,
                agvModel: agvModel.value,
                lrdistanceList: lrdistanceList.value
            },
            width: "45%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            //@ts-ignore
            contentRenderer: () => h(elForm, { ref: formRef }),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                if (!curData.prestaid) {
                    curData.prestaid = null
                }
                // 把lrdistance转换为number类型
                curData.lrdistance = Number(curData.lrdistance)
                curData.lrdistance2 = Number(curData.lrdistance2)
                function chores() {
                    message(`您${title}了货位名称为${curData.code}的这条数据`, {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        // console.log("curData", curData);
                        // 表单规则校验通过
                        if (title === "新增") {
                            console.log('curData=>', curData);

                            addLocations(curData).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else {
                            updateLocations({ ...curData, id: row.id }).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    async function openDialog(title = "新增", row?: FormItemProps) {
        // if (title === "编辑") {
        //     getLocations(row.id).then(res => {
        //         if (res.Code === 0) {
        //             // console.log('row=>', res);
        //             row.stationList = res.Content.stationList.length !== 0 ? res.Content.stationList : null
        //             newAddDialog(title, row);
        //         }
        //     })
        // } else {
        //     newAddDialog(title, row);
        // }
        newAddDialog(title, row);
    }

    // 禁用
    function handleStatus(row) {
        let typeName = row.status !== 1 ? '启用' : '禁用'
        let status = row.status === 1 ? 2 : 1
        ElMessageBox.confirm(
            `是否确认${typeName}名称为${row.code}的货位?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            let data = { id: row.id, status }
            console.log(data)
            UpdateStatus(data).then(res => {
                if (res.Code === 0) {
                    message(`您${row.status === 1 ? '禁用' : '启用'}了名称为${row.code}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    // 删除
    function delLocation(row) {
        ElMessageBox.confirm(
            `是否确认删除名称为${row.code}的货位?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            delLocations(row.id).then(res => {
                if (res.Code === 0) {
                    message(`您删除了名称为${row.code}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    // 指定货位出库
    function addAppointOut(row) {
        ElMessageBox.confirm(
            `是否确认${row.code}货位出库?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            let data = { storePlaceID: row.id }
            AppointOut(data).then(res => {
                if (res.Code === 0) {
                    message(`出库成功`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    // 导出
    function exportExcel() {
        ElMessageBox.confirm(
            `是否确认导出数据?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            excelLocations(form, '货位列表')
        }).catch(() => { })
    }

    // 手动删除货载
    function addDelteLoad(row) {
        ElMessageBox.confirm(
            `是否手动删除${row.code}货位的货载?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            let data = { id: row.id }
            DelteLoad(data).then(res => {
                if (res.Code === 0) {
                    message(`删除成功`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    // 清空出库货位
    function clearrackslocation() {
        ElMessageBox.confirm(
            `是否清空出库货位?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            EmptyOut().then(res => {
                if (res.Code === 0) {
                    message(`清空成功`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    // 初始化
    function initialize(row) {
        ElMessageBox.confirm(
            `是否初始化${row.code}货位?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            let data = { id: row.id }
            Initialize(data).then(res => {
                if (res.Code === 0) {
                    message(`初始化成功`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onBeforeMount(async () => {
        // 货架列表
        let { Content: racks } = await GetAllshelves()
        rackselect.value = racks
        // 类别列表
        let { Content: category } = await getCategory()
        categorySelect.value = category
        // 货位类型
        let { Content: attributeType } = await Attribute()
        attributeSelect.value = attributeType
        // 左右伸缩距离
        let { Content: ldristance } = await Ldristance()
        lrdistanceList.value = ldristance

        // let { Content: type } = await agvModels()
        // agvModel.value = type
    })


    onMounted(async () => {
        let { Content: type } = await agvModels()
        agvModel.value = type
        // 站点列表
        let { Content } = await GetAllStation({ status: 1, stationType: 3 })
        // let { Content } = await GetAllStation({})
        stationSelect.value = Content
        onSearch()
    })

    return {
        columns,
        loading,
        dataList,
        openDialog,
        handleStatus,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange,
        statusSelect,
        attributeSelect,
        rackselect,
        categorySelect,
        stationSelect,
        addAppointOut,
        addDelteLoad,
        clearrackslocation,
        initialize,
        delLocation,
        exportExcel,
        agvModel,
        tableReloading
    }
}